#include "Myfile_stdio.h"

#define FLAG_W "w"
#define FLAG_A "a"
#define FLAG_R "r"
#define PERM 0666

_FILE* _fopen(const char* filename, const char* flag)
{
    int fd = -1;
    
    // 判断flag
    if(strcmp(flag, FLAG_W) == 0){
        fd = open(filename, O_CREAT|O_WRONLY|O_TRUNC, PERM);
    }
    else if(strcmp(flag, FLAG_A) == 0){
        fd = open(filename, O_CREAT|O_WRONLY|O_APPEND, PERM);
    }
    else if(strcmp(flag, FLAG_R) == 0){
        fd = open(filename, O_RDONLY);
    }
    else{
        return NULL;
    }
    
    if(fd == -1) return NULL;
    _FILE* fp = (_FILE*)malloc(sizeof(_FILE));
    if(fp == NULL)
    {
        // perror("_FILE malloc fail");
        return NULL;
    }
    fp->_fileno = fd;
    fp->out_pos = 0;
    // 默认缓冲区刷新方式是 行刷新
    fp->flag = FLUSH_LINE;

    return fp;
}


int _fwrite(_FILE* fp, const char* str, int len)
{
    memcpy(&fp->outbuffer[fp->out_pos], str, len);
    fp->out_pos += len;
    
    if(fp->flag == FLUSH_NOW){
        write(fp->_fileno, fp->outbuffer, fp->out_pos);
        fp->out_pos = 0; 
    }
    else if(fp->flag == FLUSH_LINE){
        if(fp->outbuffer[fp->out_pos-1] == '\n'){
            write(fp->_fileno, fp->outbuffer, fp->out_pos);
            fp->out_pos = 0; 
        }       
    }
    else if(fp->flag == FLUSH_ALL){
        if(fp->out_pos == SIZE){
            write(fp->_fileno, fp->outbuffer, fp->out_pos);
            fp->out_pos = 0;
        }
    }   
    return len;
}

void _fflush(_FILE* fp)
{
    if(fp->out_pos > 0)
    {
        write(fp->_fileno, fp->outbuffer, fp->out_pos);
        fp->out_pos = 0;
    }
}

void _fclose(_FILE* fp)
{
    if(fp == NULL) return;
    // 刷新缓冲区
    _fflush(fp);
    close(fp->_fileno);
    free(fp);
}
